package com.tg.app.activity.device.settings;


import static com.appbase.custom.BuildConfig.SHOW_AI_SERVICE;
import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;

import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Consumer;

import com.bumptech.glide.Glide;
import com.demo.view.SettingItemCheckBoxViewEx;
import com.demo.view.SettingItemSwitchViewEx;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Instruction;
import com.tange.core.device.facade.Status;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.helper.AppHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceSettingsInfo;

public class AutoTrackingActivity extends DeviceSettingsBaseActivity{
    private static final String TAG = AutoTrackingActivity.class.getSimpleName();
    private DeviceFacade deviceFacade;
    private DeviceSettingsInfo info;
    private SettingItemSwitchViewEx swAuto;
    private boolean mChecked = false;
    private DeviceFeature mDeviceFeature;
    private boolean isSupportBody;
    private SettingItemCheckBoxViewEx checkBoxAI;
    private boolean isAiEnable = false;

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onSetupFailed() {
        swAuto.setChecked(mChecked);
    }

    private void registerICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().observeOnReceive(instructionConsumer);
        }
    }

    private void unregisterICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().unObserveOnReceive(instructionConsumer);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        hideActionBar();
        setContentView(R.layout.activity_auto_track);

        String uuid = getIntent().getStringExtra(Camera.EXT_UUID);
        deviceFacade = new DeviceFacade(uuid);
        registerICameraListener();
        deviceFacade.connect();
        mDeviceFeature = DeviceFeatureObjectBox.queryDeviceFeature(uuid);
        isSupportBody = DeviceFeatureHelper.supportTrackingCloseup(mDeviceFeature);
        info = getIntent().getParcelableExtra(EXT_DEVICE_INFO);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        findViewById(R.id.back_toolbar).setOnClickListener(v -> finish());

        ImageView autoImage = findViewById(R.id.iv_auto_track);
        Glide.with(this).asGif().load(R.mipmap.auto_track).into(autoImage);
        swAuto = findViewById(R.id.sw_auto_track);
        checkBoxAI = findViewById(R.id.cb_auto_track);

        setAILayout(false);
        swAuto.setOnClickListener(v -> {
            if (!TGDevice.getInstance().isNetwork(deviceFacade)) {
                swAuto.setChecked(!swAuto.isChecked());
                showToast(R.string.txt_network_anomaly);
                return;
            }
            mChecked = !swAuto.isChecked();
            if (mDeviceFeature != null) {
                if (info != null) {
                    if (swAuto.isChecked() && checkBoxAI.isChecked()) {
                        setAutoTrackCmd(1, 1);
                    } else if (swAuto.isChecked()) {
                        setAutoTrackCmd(1, -1);
                    } else {
                        setAutoTrackCmd(0, -1);
                    }
                } else {
                    if (swAuto.isChecked()) {
                        setAutoTrackCmd(1, -1);
                    } else {
                        setAutoTrackCmd(0, -1);
                    }
                }
            } else {
                if (swAuto.isChecked()) {
                    setAutoTrackCmd(1, -1);
                } else {
                    setAutoTrackCmd(0, -1);
                }
            }
        });
        swAuto.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                showAILayout();
            } else {
                setAILayout(false);
            }
        });
        mChecked = swAuto.isChecked();
        if (mChecked) {
            showAILayout();
        }

        checkBoxAI.setOnClickListener(v -> {
            if (checkBoxAI.isChecked()) {
                setAutoTrackCmd(1, 1);
            } else {
                setAutoTrackCmd(1, 0);
            }
        });
    }

    private boolean showAI(){
        if (!SHOW_AI_SERVICE){
            return true;
        }
        if (info!=null){
            return  info.ai_service;
        }
        return  false;
    }
    private void showAILayout() {
        if (mDeviceFeature != null && isSupportBody) {
            setAILayout(true);
        }
    }

    private void getAiEnable() {
        if (!isAiEnable){
            isAiEnable = true;
            startSendui();
            if (DeviceFeatureHelper.supportAiSwitch(mDeviceFeature)) {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_AI_REQ, new byte[1]);
            } else {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_ENABLE_BT_REQ, new byte[1]);
            }
        }

    }

    private boolean isSupportTrackingCloseup() {
        return DeviceFeatureHelper.supportTrackingCloseup(mDeviceFeature);
    }

    private void setAILayout(boolean show) {
        checkBoxAI.setVisibility(show ? View.VISIBLE : View.GONE);
        swAuto.showLine(show);
    }

    private void initData() {
        if (info != null) {
            mChecked = isAutoTrackOpen();
            swAuto.setChecked(mChecked);
            if (deviceFacade.connected()){
                getAiEnable();
            }

        }
    }

    private void setAutoTrackCmd(int type, int bt) {
        info.autoTracking = type;
        AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_MOTION_TRACKER_REQ, AVIOCTRLDEFs.SMsgAVIoctrlSetMotionTrackerReq.parseContent(type));
        if (bt != -1 && isSupportBody) {
            if (DeviceFeatureHelper.supportAiSwitch(mDeviceFeature)) {
                int mask = 1 << 1;
                int flag = bt << 1;
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_SET_AI_REQ, AVIOCTRLDEFs.Tcis_AiStatus.parseContent(mask, flag));
            } else {
                AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_SET_ENABLE_BT_REQ, AVIOCTRLDEFs.Tcis_SetEnableBtReq.parseContent(bt));
            }
        }
    }

    private void setCloseupTrackCmd(int enabled) {
        AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_SET_ENABLE_CLOSEUP_REQ, AVIOCTRLDEFs.Tcis_EnableCloseup.parseContent(0, enabled));
    }

    private void getCloseupTrackCmd() {
        AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.TCI_CMD_GET_ENABLE_CLOSEUP_REQ, AVIOCTRLDEFs.Tcis_EnableCloseup.parseContent(0, 0));
    }

    private boolean isAutoTrackOpen() {
        return info != null && info.autoTracking == 1;
    }

    private final Consumer<ConnectStatus> connectStatusConsumer = connectStatus -> {
        if (connectStatus.getStatus() == Status.SUCCESS){
            TGLog.d(TAG,"连接成功");
            getAiEnable();
        }else if (connectStatus.getStatus() == Status.FAILED){
            TGLog.d(TAG,"连接失败");
        }
    };

    private final Consumer<Instruction> instructionConsumer = instruction -> {
        if (instruction == null) {
            return;
        }
        final int type = instruction.getId();
        final byte[] data = instruction.getData();
        receiveIOCtrlData(type, data);
    };

    public void receiveIOCtrlData(final int type, final @NonNull byte[] data) {
        runOnUiThread(() -> {
            completeSend();
            TGLog.d(TAG,"type == " + type);
            if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_MOTION_TRACKER_RESP) {
                mChecked = swAuto.isChecked();
                sendUpdateSettingBroadcast(info);
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_ENABLE_BT_RESP) {
                if (!isSupportBody&&!info.ai_service)return;
                isSupportBody = true;
                int enable = Packet.byteArrayToInt_Little(data, 0);
                updateUI(enable);
            } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
                int cmd = Packet.byteArrayToInt_Little(data, 0);
                TGLog.d(TAG,"cmd = " + cmd);
                int enable = Packet.byteArrayToInt_Little(data, 4);
                if (enable == 3) {
                    swAuto.setChecked(isAutoTrackOpen());
                }else {
                    sendUpdateSettingBroadcast(info);
                }
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_AI_RESP) {
                if (!isSupportBody&&!info.ai_service)return;
                int mask = Packet.byteArrayToInt_Little(data, 0) >> 1 & 1;
                int flag = Packet.byteArrayToInt_Little(data, 4);
                int flags = flag >> 1 & 1;
                if (mask == 1) {
                    isSupportBody = true;
                }
                updateUI(flags);
                TGLog.i(TAG, "mask " + Integer.toBinaryString(mask) + " flags: " + Integer.toBinaryString(flags));
            }
        });

    }

    private void updateUI(int enable) {
        swAuto.setChecked(isAutoTrackOpen());
        checkBoxAI.setChecked(enable == 1);
        mChecked = swAuto.isChecked();
        if (isAutoTrackOpen()){
            showAILayout();
            if (enable == 1){
                getCloseupTrackCmd();
            }
        }

    }
}
